﻿Shader "Demon/OutLine/OutLine_Backface"
{
	Properties
	{
		_MainTex ("Texture", 2D) = "white" {}
		[Header(OutLine)]
		_Width("Width(描边宽度)",Range(0,1)) = 0.1
		_OutLineColor("OutLineColor(描边颜色)",Color) = (0,0,0,1)
		_DepthBias("DepthBias",Range(-0.1,0.1)) = 0
	}
	SubShader
	{
		Tags { "RenderType"="Opaque" }
		LOD 100

		// 第一个pass为描边
		Pass
		{
			Cull Front

			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag

			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float3 normal : NORMAL;
			};

			struct v2f
			{
				float4 vertex : SV_POSITION;
			};

			float _Width;
			float4 _OutLineColor;
			float _DepthBias;
			
			v2f vert (appdata v)
			{
				v2f o;
				float width = _Width * 0.01;
				//1、单纯往法线方向挤出 
				// width = normalize(v.normal) * width;// * v.vertex.w * 2;
				// v.vertex += width;
				
				o.vertex = UnityObjectToClipPos(v.vertex);

				//2、沿屏幕方向挤出描边
				float3 clipNormal = UnityObjectToClipPos(v.normal);
				o.vertex.xy += normalize(clipNormal.xy) / normalize(_ScreenParams.xy) * width * o.vertex.w * 2;
				//_DepthBias 当不使用前向剔除的时候 可以在 z 轴方向做加减，把挤出的描边想向模型方向的背后移动
				//以实现仅外轮廓的描边(会缺少内部描边)
				//o.vertex.z += _DepthBias;
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				return _OutLineColor;
			}
			ENDCG
		}

		Pass
		{
			CGPROGRAM
			#pragma vertex vert
			#pragma fragment frag
			// make fog work
			#pragma multi_compile_fog
			
			#include "UnityCG.cginc"

			struct appdata
			{
				float4 vertex : POSITION;
				float2 uv : TEXCOORD0;
			};

			struct v2f
			{
				float2 uv : TEXCOORD0;
				UNITY_FOG_COORDS(1)
				float4 vertex : SV_POSITION;
			};

			sampler2D _MainTex;
			float4 _MainTex_ST;
			
			v2f vert (appdata v)
			{
				v2f o;
				o.vertex = UnityObjectToClipPos(v.vertex);
				o.uv = TRANSFORM_TEX(v.uv, _MainTex);
				UNITY_TRANSFER_FOG(o,o.vertex);
				return o;
			}
			
			fixed4 frag (v2f i) : SV_Target
			{
				// sample the texture
				fixed4 col = tex2D(_MainTex, i.uv);
				// apply fog
				UNITY_APPLY_FOG(i.fogCoord, col);
				return col;
			}
			ENDCG
		}
	}
}
